# Jinja2 Templates 用户定义的过滤器
# ============================================================================
import re
from datetime import datetime
from typing import Union

from fastapi import Request
from starlette.datastructures import URL


def datetime_format(date: datetime, format="%Y-%m-%d %H:%M:%S"):
    """将日期转换为指定格式"""
    if not date or not isinstance(date, datetime):
        return ""

    return date.strftime(format)


def number_format(number: int) -> str:
    """返回由一千分隔的数字

    Args:
        number (int): 编号

    Returns:
        str: 以千分隔的数字
    """
    if isinstance(number, int):
        return "{:,}".format(number)

    return "0"


def search_font(content: str, stx: str) -> str:
    """搜索词的指定字体的颜色, 替换为背景色

    Args:
        content (str): 搜索目标字符串
        stx (str): 搜索词

    Returns:
        str: 为其指定搜索词的字体的颜色, 由背景颜色替换的字符串
    """
    # 在字符之前 \附加.
    src = ['/', '|']
    dst = ['\\/', '\\|']

    if not stx or not stx.strip() and stx != '0':
        return content

    # 整个搜索词被分成空格
    search_keywords = stx.split()

    # "(搜索1|搜索2)"创建一个模式，如.
    pattern = ''
    bar = ''
    for keyword in search_keywords:
        if keyword.strip() == '':
            continue
        tmp_str = re.escape(keyword)
        tmp_str = tmp_str.replace(src[0], dst[0]).replace(src[1], dst[1])
        pattern += f'{bar}{tmp_str}(?![^<]*>)'
        bar = "|"

    # 指定搜索字体的颜色, 替换为背景色
    replace = "<b class=\"sch_word\">\\1</b>"

    return re.sub(f'({pattern})', replace, content, flags=re.IGNORECASE)


def set_query_params(url: Union[URL, str], request: Request,
                     remove: list = [], **params: dict) -> URL:
    """url开 query string添加

    Args:
        url (Union[URL, str]): URL
        request (Request): FastAPI Request 对象
        remove (list): 要删除 query string
        **params (dict): 要添加 query string

    Returns:
        URL: query string添加了这个 URL
    """
    url = URL(url) if isinstance(url, str) else url

    query_params = request.query_params._dict
    # 要删除 query string删除
    for key in remove:
        query_params.pop(key, None)

    # query_params和 params优点
    set_params = {**query_params, **params}

    # 电流 query string在维护的同时添加 query string添加
    url = url.replace_query_params(**set_params)

    return url
